package gitobject;
import repository.Repository;
import zlib.ZLibUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


public class GitObject {
    protected String name;
    protected String fmt;                  //type of object
    protected String key;                  //key of object
    protected String mode;                 //mode of object
    protected File file;                   //file为工作区中的文件
    protected String path = Repository.getGitDir() + File.separator + "objects";
    //absolute path of objects  , path 为静态变量
    protected String value;
    //value of object

    public String getFmt(){
        return fmt;
    }
    public String getKey() { return key; }
    public String getMode(){ return mode;}
    public String getPath() {
        return path;
    }
    public String getValue(){ return value; }
    public String getName(){ return name;}


    public void setName(String name){
        this.name = name;
    }





    public GitObject(){}  //构造函数
    /**
     * Get the value(content) of file
     * 直接调用Files类函数，readAllBytes,该方法不可用于读取大文件
     * @param file
     * @return String
     * @throws IOException
     */
    //将文件读入字符串;Java源程序为文本文件，类程序为二进制文件
    public static String getValue(File file) throws IOException {
        String file_path = file.getAbsolutePath();
        Path path = Paths.get(file_path);
        return new String(Files.readAllBytes(path));
    }

    /**
     * Todo: Serialize the object to the local repository.
     * @throws Exception
     */
    //自定义writeObject()方法,
    public void writeObject() throws Exception{
      //  String Id = this.mode + " " + this.fmt + " " + this.key + this.file.getName() + " " + "object";
        FileOutputStream fos = new FileOutputStream(this.path + File.separator + this.key);
        //文件数据流os指向File_Path，path为生成二进制文件的路径,key为二进制文件名称
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //对象数据流oos指向fos,在oos上操作生成序列化文件
        oos.writeObject(this.value);//序列化文件内容
        oos.close();//关闭对象数据流
    }

    /**
     * Todo: Serialize the object and compress with zlib.
     * @throws Exception
     */
    public void compressWrite() throws Exception{
        String fileValue = this.value;
        byte[] strbyte = fileValue.getBytes();
        //将value 转化为字节数组
        byte[] compressed_byte = ZLibUtils.compress( strbyte );
        //调用ZlibUtils抽象类中compress()函数生成压缩后的字符串compressed_byte
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path + File.separator + this.key));
        //创建对象数据流 oos 指向文件对象流，oos指向path + this.key处
        ZLibUtils.compress(compressed_byte,oos);
        //调用compress()函数，在数据流oos指向的位置生成含有压缩后字节数组compressed_byte的压缩文件
        //文件名为path + this.key
    }

}
